import chalk from 'chalk';
import Chance from 'chance';
const chance = new Chance();

// 扩展日志类型，添加权重
const logTypes = [
  {
    color: chalk.green,
    weight: 10, // 出现概率权重，数值越大出现概率越高
    text: () => `Operation completed successfully. All systems are operational. Last operation took ${chance.integer({min: 10, max: 100})} ms to complete.`
  },
  {
    color: chalk.yellow,
    weight: 20,
    text: () => `Warning: System performance degraded. Current CPU usage: ${chance.integer({min: 70, max: 95})}%. Memory usage: ${chance.integer({min: 60, max: 90})}%.`
  },
  {
    color: chalk.red,
    weight: 5,
    text: () => `Critical Error: System halted. Error code: ${chance.integer({min: 500, max: 599})} @ ${chance.paragraph()}. Affected module: ${chance.word()}.`
  },
  {
    color: chalk.blue,
    weight: 20,
    text: () => `Debugging: Processing request... Searching for inconsistencies in file ${chance.string({length: 8})}. User: ${chance.name()}.`
  },
  {
    color: chalk.magenta,
    weight: 15,
    text: () => `Info: System uptime increased. Running for ${chance.hour()} hours and ${chance.minute()} minutes. Current session ID: ${chance.guid()}.`
  },
  {
    color: chalk.white,
    weight: 40,
    text: () => `Log Entry: ${chance.paragraph()} Timestamp: ${new Date().toISOString()}`
  },
  {
    color: chalk.cyan,
    weight: 10,
    text: () => `Network: Incoming connection from ${chance.ip()}. Data transfer rate: ${chance.integer({min: 100, max: 1000})} KB/s.`
  },
  {
    color: chalk.gray,
    weight: 5,
    text: () => `Security: Unauthorized access attempt detected. IP: ${chance.ip()}. User: ${chance.name()}.`
  }
];

// 动态进度条函数
const generateProgressIndicator = () => {
  const progress = [];
  for (let i = 0; i < chance.integer({min: 5, max: 20}); i++) {
    progress.push('.');
  }
  return progress.join('');
};

// 模拟下载进度
const simulateDownload = () => {
  const fileName = `file_${chance.string({ length: 8, pool: 'abcdefghijklmnopqrstuvwxyz' })}.zip`;
  const fileSize = chance.integer({ min: 50, max: 500 }); // 文件大小，单位为MB
  const minDownloadTime = 15 * 1000; // 最小下载时间为15秒
  const maxDownloadTime = 60 * 1000; // 最大下载时间为1分钟
  const downloadTotalTime = chance.integer({ min: minDownloadTime, max: maxDownloadTime });
  let downloadProgress = 0;
  let downloadedSize = 0;

  console.log(`Starting download of ${fileName} (${fileSize} MB)...`);

  const downloadTimer = setInterval(() => {
    const downloadSpeed = chance.integer({ min: 1, max: 3 }); // 调整下载速度，单位为MB/s
    downloadedSize += downloadSpeed;
    downloadProgress = Math.min((downloadedSize / fileSize) * 100, 100);
    const barLength = 40;
    let filledLength = Math.round((downloadProgress / 100) * barLength);
    filledLength = Math.min(filledLength, barLength);
    const bar = chalk.blue('#'.repeat(filledLength)) + ' '.repeat(barLength - filledLength);
    
    // 使用 \r 覆盖当前行
    process.stdout.write(`\rDownloading: [${bar}] ${downloadProgress.toFixed(2)}% Complete at ${downloadSpeed} MB/s`);

    if (downloadProgress >= 100) {
      clearInterval(downloadTimer);
      console.log(chalk.green(`\nDownload of ${fileName} completed!`)); // 换行显示下载完成信息
      setTimeout(printLog, chance.integer({ min: 100, max: 1000 }));
    }
  }, 1000); // 每秒更新一次进度
};

// 选择日志类型，基于权重
const chooseLogType = () => {
  let totalWeight = logTypes.reduce((acc, type) => acc + type.weight, 0);
  let randomNumber = chance.integer({ min: 0, max: totalWeight - 1 });
  for (let type of logTypes) {
    randomNumber -= type.weight;
    if (randomNumber < 0) {
      return type;
    }
  }
  return logTypes[0]; // 默认返回第一个日志类型，以防万一
};

function printLog() {
  const logType = chooseLogType();
  let message = `[${new Date().toISOString()}] ${logType.color(logType.text())}`; // 添加时间戳

  if (chance.bool({ likelihood: 50 })) {
    message += ` ${chalk.grey(generateProgressIndicator())}`;
  }

  if (chance.bool({ likelihood: 1 })) {
    simulateDownload();
    return;
  }

  console.log(message);

  setTimeout(printLog, chance.integer({ min: 100, max: 1000 }));
}

// 启动日志打印
printLog();
